package com.tracesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tracesystem.commons.Result;
import com.tracesystem.controller.form.*;
import com.tracesystem.controller.info.SimpleUserInfo;
import com.tracesystem.model.IssueUser;
import com.tracesystem.dao.IssueUserDao;
import com.tracesystem.service.IssueUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tracesystem.util.WoniuCopyUtil;
import com.tracesystem.util.exception.IssueUserException;
import com.tracesystem.util.exception.code.IssueUserExceptionCode;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-23
 */
@Service
public class IssueUserServiceImpl extends ServiceImpl<IssueUserDao, IssueUser> implements IssueUserService {

    /**
     * 账号实现层对象
     */
    @Resource
    private IssueUserDao issueUserDao;
    /**
     * 账号业务层对象
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateIssueUser(UpdateUserForm updateUserForm) {
        IssueUser user = getOne(//查询用户是否存在
                new QueryWrapper<IssueUser>().eq("USER_id", updateUserForm.getUserId()));
        //不存在则抛出已存在异常
        if (null == user) throw new IssueUserException(IssueUserExceptionCode.IssueUser_NOTEXIST_ERROR);
        if (user.getUserEmail() != updateUserForm.getUserEmail() || user.getUserTel() != updateUserForm.getUserTel()) {
            user.setUserEmail(updateUserForm.getUserEmail());
            user.setUserTel(updateUserForm.getUserTel());
        } else {
            throw new IssueUserException(IssueUserExceptionCode.IssueUser_CANTUPDATA_ERROR);
        }
        boolean b = updateById(user);
        if(b) return Result.getInstance().setMsg("修改成功");
        else throw new IssueUserException(IssueUserExceptionCode.IssueUser_UPDATA_ERROR);
    }

    @Override
    public Result<Page<SimpleUserInfo>> findUserPage(GetUserPageForm UserPageForm) {
        QueryWrapper<IssueUser> queryWrapper =null;
        //查询两个字段中符合模糊条件的数据
        if(UserPageForm.getUsername()!=null&&UserPageForm.getUsername().trim()!=""){
            queryWrapper=new QueryWrapper<>();
            queryWrapper.like("USERNAME",UserPageForm.getUsername());
        }
        Page<IssueUser> page = page(new Page<>(UserPageForm.getPageIndex(), UserPageForm.getPageSize()), queryWrapper);
        List<IssueUser> records = page.getRecords();
        if(null==records||records.size()==0)throw new IssueUserException(IssueUserExceptionCode.IssueUser_NOTEXIST_ERROR);
        List<SimpleUserInfo> SimpleUserInfos = WoniuCopyUtil.copyMany(records, SimpleUserInfo.class);
        Page<SimpleUserInfo> simpleUserInfoPage = new Page<>();
        simpleUserInfoPage.setRecords(SimpleUserInfos)
                .setPages(page.getPages())
                .setCurrent(page.getCurrent())
                .setTotal(page.getTotal())
                .setSize(page.getSize());
        return Result.getInstance(Page.class).setData(simpleUserInfoPage).setMsg("查询成功");

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result ReWitePassword(ChangePasswordForm changePasswordForm) {
        IssueUser user = getById(changePasswordForm.getUserId());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (bCryptPasswordEncoder.matches(changePasswordForm.getOldpass(), user.getPassword())) {
            if (changePasswordForm.getPass().equals(changePasswordForm.getCheckPass())) {
                if (bCryptPasswordEncoder.matches(changePasswordForm.getPass(), user.getPassword()))
                    throw new IssueUserException(IssueUserExceptionCode.ISSUEUSER_SAMEPASSWORD_ERROR);
                user.setPassword(bCryptPasswordEncoder.encode(changePasswordForm.getPass()));
                updateById(user);
                return Result.getInstance().setMsg("修改密码成功");
            } else throw new IssueUserException(IssueUserExceptionCode.IssueUser_DIFPASSWORD_ERROR);
        } else throw new IssueUserException(IssueUserExceptionCode.IssueUser_PASSWORD_ERRORR);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> cutUser(RmUserForm rmUserForm) {
        int i = issueUserDao.deleteById(rmUserForm.getUserId());
        if (i == 1) {
            return Result.getInstance().setMsg("删除成功");
        } else {
            throw new IssueUserException(IssueUserExceptionCode.IssueUser_NOTEXIST_ERROR);
        }
    }

    @Override
    public Result saveUser(InsertUserForm insertUserForm) {
        IssueUser user = getOne(//查询用户是否存在
                new QueryWrapper<IssueUser>().eq("USERNAME", insertUserForm.getUsername()));
        //存在则抛出已存在异常
        if (null != user) throw new IssueUserException(IssueUserExceptionCode.IssueUser_EXIST_ERROR);
        //spring security中的BCryptPasswordEncoder方法
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //加密密码
        insertUserForm.setPassword(bCryptPasswordEncoder.encode(insertUserForm.getPassword()));
        save(WoniuCopyUtil.copyOne(insertUserForm, IssueUser.class));
        return Result.getInstance().setMsg("新增成功");

    }
}
